# -*- coding: utf-8 -*-
import os
import time

import mss
import numpy as np
import pyautogui
import cv2
import tms.util.location as location
from paddleocr import PaddleOCR

area = {"left": 924, "top": 44, "width": 720, "height": 1315}
left = area['left']
top = area['top']
img_path = '/sam/img/'
shot_path = '/sam/shot/'
btn_imgs_dict = {
    'to_select_city_page': ['to_select_city_page.png', 'to_select_city_page_1.png']
}

# 点击按钮
def click(type, top=5, left=5, t=1, i=0):
    cut_main_gray = get_main_gray()
    if type in btn_imgs_dict:
        btn_imgs = btn_imgs_dict[type]
        for img in btn_imgs:
            result = click_img(cut_main_gray, img, top, left, t, i)
            if result:
                return True
        return False
    else:
        img = type + '.png'
        return click_img(cut_main_gray, img, top, left, t, i)

# 执行按钮点击
def click_img(cut_main_gray, img, left=10, top=10, t=1, i=0):
    img_gray = cv2.cvtColor(cv2.imread(os.getcwd() + img_path + img), cv2.COLOR_BGR2GRAY)
    # 将结果再次处理，仅保留坐标值
    locations = location.getlocations(cut_main_gray, img_gray)
    if len(locations) > 0 and len(locations) > i:
        click_position(locations[i][0] + left, locations[i][1] + top)
        time.sleep(t)
        return True
    return False

# 点击指定坐标，加上偏移量
def click_position(x, y, t=0.01):
    pyautogui.click(left + x, top + y)
    time.sleep(t)

def paste(locations, t=0.1):
    click_position(locations[0], locations[1])
    pyautogui.mouseDown(button='left')
    time.sleep(2)
    pyautogui.mouseUp(button='left')
    time.sleep(0.5)
    click('paste')
    time.sleep(t)

def moveTo(x, y):
    pyautogui.moveTo(left + x, top + y)

# 点击指定坐标，加上偏移量
def dragTo(x, y, t):
    pyautogui.dragTo(left + x, top + y, t)

def keyup(key):
    time.sleep(0.01)
    pyautogui.keyUp(key)

def keydown(key):
    time.sleep(0.01)
    pyautogui.keyDown(key)

def scroll(clicks):
    time.sleep(0.01)
    pyautogui.scroll(clicks)

def get_main_gray(a=area):
    with mss.mss() as sct:
        cut_main = sct.grab(a)
        cut_main = np.array(cut_main)
        # 转成灰度，更快查找
        cut_main_gray = cv2.cvtColor(cut_main, cv2.COLOR_BGR2GRAY)
        return cut_main_gray

def show_main(a=area):
    with mss.mss() as sct:
        cut_main = sct.grab(a)
        cut_main = np.array(cut_main)
        cv2.imshow("sam", cut_main)
        if cv2.waitKey(5) & 0xFF == ord("q"):
            cv2.destroyAllWindows()

# 判断指定区域有没有指定图片
def has_img(img, a=area):
    cut_main_gray = get_main_gray(a)
    img_gray = cv2.cvtColor(cv2.imread(os.getcwd() + img_path + img), cv2.COLOR_BGR2GRAY)
    # 将结果再次处理，仅保留坐标值
    locations = location.getlocations(cut_main_gray, img_gray)
    if len(locations) > 0:
        return True
    else:
        return False

def cut_screen(a):
    with mss.mss() as sct:
        cut_main = sct.grab(a)
        cut_main = np.array(cut_main)
        file_path = os.getcwd() + shot_path + '/shot.jpg'
        cv2.imwrite(file_path, cut_main)
        return file_path

# 选择文本
def choose_text(text, t=0.5):
    max_time = 20
    index = 0
    while True:
        if index >= max_time:
            return False
        pos = get_text_position(text)
        if pos is not None:
            click_position(pos[0] + 10, pos[1])
            time.sleep(t)
            return True
        else:
            moveTo(420, 860)
            scroll(-100)
            index += 1

# 获取文本所在坐标
def get_text_position(text, a=area):
    ocr = PaddleOCR(use_angle_cls=True)
    result = ocr.ocr(cut_screen(a), cls=True)
    for idx in range(len(result)):
        res = result[idx]
        if res is None:
            return None
        for line in res:
            t = line[1][0]
            if (text in t):
                return line[0][0]
    return None